<template>
  <div class="report-container">
    <el-tabs v-model="query.month" @tab-click="fetchData">
      <el-tab-pane v-for="(item, index) in tabTitles" :key="index" :label="item.text" :name="item.value"></el-tab-pane>
    </el-tabs>
    <div class="report-header">
      <el-tag type="info">一、入库垃圾量及成分</el-tag>
      <div v-show="miniPanelShow">
        <el-tooltip content="导出excel">
          <el-button size="mini" v-loading="downloadLoading"  circle @click.native="remoteExport">
            <svg-icon icon-class="f-export" class-name="im-ex-icon" />
          </el-button>
        </el-tooltip>
        <el-tooltip content="固定/拉伸表格">
          <el-button size="mini"  :icon="resizeForm?'el-icon-unlock':'el-icon-lock'" circle @click.native="resizedFormAct" />
        </el-tooltip>
      </div>
    </div>
    <el-table :data="reportData"
              style="width: 100%"
              v-loading="tableLoading"
              element-loading-text="报表生成中..."
              element-loading-spinner="el-icon-loading"
              :height="tableHeight">
      <el-table-column v-for="(col,idx) in reportCols" :key="idx" :prop="col.prop" :label="col.label" :type="col.type" :width="col.width" :fixed="col.fixed" align="center">
        <el-table-column v-for="(child, index) in col.children" :key="index" :prop="child.prop" :label="child.label" align="center"></el-table-column>
      </el-table-column>
    </el-table>
  </div>

</template>

<script>
  import analysisApi from "@/api/analysis"
  import {formMonths} from "@/utils/constants"
  export default {
    name: "ljl-report",
    props:{
      query:{
        type:Object,
        required:true
      }
    },
    data(){
      return {
        formMonths,
        miniPanelShow:true,
        tableLoading:false,
        downloadLoading: false,
        resizeForm:false,
        content:'暂无报表数据!',
        tableHeight:'500',
        reportCols:[],
        reportData: []
      }
    },
    computed:{
      tabTitles(){
        const lastTab = {
          text:'年度',
          value:'all'
        }
        return [...this.formMonths, lastTab]
      },
      excelFileName(){
        return this.query.module_name+this.query.year.substring(0,4)+this.query.month
      }
    },
    methods:{
      fetchData(){
        if (!this.query.orgnization_ids.length){
          this.$message.warning("请选择组织!")
          this.miniPanelShow=false
          this.reportData=[]
          return
        }
        let rqParams = Object.assign({},this.query)
        rqParams.orgnization_id = rqParams.orgnization_ids.join(",")
        const yearCom = rqParams.year.split('-')
        if (yearCom.length>1)
          rqParams.year = yearCom[0]
        delete rqParams['orgnization_ids']
        this.tableLoading=true
        analysisApi.analysisReport(rqParams).then(res=>{
          const tableData = this.convertData(res.data)
          this.reportCols = tableData[0]
          setTimeout(()=>{
            this.reportData = tableData[1]
            this.tableHeight = window.innerHeight-280
            this.miniPanelShow=true
            this.tableLoading=false
          },200)
        })
      },
      convertData(dataList){
        let tbCols=[]
        let tbArr=[]
        for (let idx in dataList){
          const data = dataList[idx]
          if (idx=='0'){
            tbCols.push({
              prop:null,
              width:'60',
              label:'序号',
              type: 'index',
              children:[],
              fixed:true
            })
            tbCols.push({
              prop:'orgnization_name',
              label:'项目',
              children:[],
              fixed:true
            })
            for (let tag of data.data){
              tbCols.push({
                prop:null,
                label:tag.dcs_standard_name,
                fixed:false,
                children:[{
                  prop:tag.en_name,
                  label:tag.messure
                }]
              })
            }
          }
          let tbEntity = {orgnization_name:data.orgnization_name}
          for (let tag of data.data){
            tbEntity[tag.en_name] = tag.value
          }
          tbArr.push(tbEntity)
        }
        return [tbCols,tbArr]
      },
      resizedFormAct(){
        this.resizeForm = !this.resizeForm
        if (!this.resizeForm){
          this.tableHeight=window.innerHeight-280
          this.$message.success("您固定了表格")
        } else{
          this.tableHeight=2600
          this.$message.success("您取消了表格固定")
        }
      },
      localExport(){
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          let multiHeader = []
          let header = []
          for (let col of this.reportCols){
            if (col.type=='index')
              continue
            multiHeader.push(col.label)
            if (col.children.length)
              header.push(col.children[0].label)
            else
              header.push("")
          }
          multiHeader = [multiHeader]
          const list = this.reportData
          const data = list.map(v => Object.values(v))
          const merges = ['A1:A2']
          const exportJson={
            filename:this.excelFileName,
            multiHeader,
            header,
            merges,
            data
          }
          excel.export_json_to_excel(exportJson)
          this.$message.success("导出excel成功")
          this.downloadLoading = false
        })
      },
      async remoteExport(){
        const downLoading = this.$loading({
          lock: true,
          text: '导出中...',
          spinner: 'el-icon-loading',
        });
        const token = await this.$store.dispatch('user/refreshToken')
        const baseHost = 'http://analysisapi.wm-mis.com/api'
        const orgnization_id = this.query.orgnization_ids.join(",")
        let year = this.query.year
        const yearCom = this.query.year.split('-')
        if (yearCom.length>1)
          year = yearCom[0]
        const durl = `${baseHost}/data-analysis/download?token=${token}&orgnization_id=${orgnization_id}&module_name=${this.query.module_name}&year=${year}&month=${this.query.month}`
        window.open((durl),"_self")
        setTimeout(()=>{
          downLoading.close()
        },1500)
      },

    }

  }
</script>

<style scoped lang="scss">
  .report-container{
    padding: 5px;
    .report-header{
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content:space-between;
      align-items: center;
    }

  }
</style>
